import { downloadFile, getBase64WithBlob, getUrlWithBlob } from '@/utils/file'
import { ref, unref } from 'vue'
import { PDFDocument } from 'pdf-lib'
import { watermark } from '@/utils/watermark'

export const usePdfWatermark = () => {
  const resBlob = ref()

  /**
   * @description pdf文件添加水印
   * @param bytes 原始文件的arrarybuffer文件流
   * @param waterText 水印文本，可选
   */
  const pdfWatermark = async (bytes: ArrayBuffer, waterText = 'mm system watermark') => {
    // 加载原始文件的unit64Arrary文件流
    const pdfDoc = await PDFDocument.load(bytes)
    // 获取水印图片的base64
    const blob: Blob = (await watermark(document.createElement('canvas'), waterText)) as Blob
    const base64: string = await getBase64WithBlob(blob)
    // 处理水印图片
    const image = await pdfDoc.embedPng(base64)
    const sacleImage = image.scale(0.5)
    // 添加水印图片
    const pages = pdfDoc.getPages()
    for (let p = 0; p < pages.length; p++) {
      const page = pages[p]
      const { width, height } = page.getSize()
      for (let y = 0; y < height; ) {
        for (let x = 0; x < width; ) {
          await page.drawImage(image, {
            x,
            y,
            width: sacleImage.width,
            height: sacleImage.height,
          })
          x += sacleImage.width
        }
        y += sacleImage.height
      }
    }
    // 获取处理后文件的unit64Arrary文件流
    const resBuffer = await pdfDoc.save()
    resBlob.value = new Blob([resBuffer], { type: 'application/pdf' })
  }

  const savePdf = (fileName: string) => {
    const url = getUrlWithBlob(unref(resBlob))
    downloadFile(url, fileName)
  }

  return {
    pdfWatermark,
    savePdf,
  }
}
